package com.example.pacs.service.impl;

import com.example.pacs.bean.entity.Instance;
import com.example.pacs.constants.PacsConstants;
import com.example.pacs.dao.InstanceMapper;
import com.example.pacs.enums.PacsExceptionEnum;
import com.example.pacs.exception.PacsException;
import com.example.pacs.service.HomeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.dcm4che3.tool.dcm2jpg.Dcm2Jpg;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;

@Service
@Slf4j
public class HomeServiceImpl implements HomeService {

    @Value("${pacs.storage.dir}")
    private String pacsStorageDir;

    @Resource
    private InstanceMapper instanceMapper;

    @Override
    public ResponseEntity<byte[]> getInstanceDetails(Long instanceId) {
        // 根据实例主键查询实例是否存在
        Instance instance = instanceMapper.selectByPrimaryKey(instanceId);
        if (instance != null) {
            File file = new File(pacsStorageDir + "/" + instance.getMediaStorageSopInstanceUid() + PacsConstants.DCM_SUFFIX);
            Dcm2Jpg dcm2Jpg ;
            final HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.IMAGE_JPEG);
            try {
                dcm2Jpg = new Dcm2Jpg();
                // 初始化dcm2Jpg
                dcm2Jpg.initImageWriter("JPEG", "jpeg", null, null, null);
                // 将文件.dcm后缀转为.jpg
                String jpgFileName = FilenameUtils.removeExtension(file.getName()) + PacsConstants.JPG_SUFFIX;
                // 创建一个JPG文件模板
                File imageTemplate = new File(pacsStorageDir, jpgFileName);
                // 将dicom file 转换为jpg文件
                dcm2Jpg.convert(file, imageTemplate);
                if (!imageTemplate.exists()) {
                    throw new PacsException(PacsExceptionEnum.JPG_FILE_NOT_EXISTS);
                }
                byte[] bytes = IOUtils.toByteArray(new FileInputStream(imageTemplate));
                return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.CREATED);
            } catch (Exception e) {
                log.error("dcmFile conversion image error!,errMsg:" + e.getMessage(), e);
            }
        }
        log.error("没有对应实例ID为:{}的实例", instanceId);
        return null;
    }
}
